from typing import List, Optional
from sqlalchemy.orm import Session
from app.models.item import ItemModel, ItemCreate, ItemUpdate
from app.config.logger import logger

class Database:
    def __init__(self, db: Session):
        self.db = db

    def get_all_items(self) -> List[ItemModel]:
        return self.db.query(ItemModel).all()

    def get_item(self, item_id: int) -> Optional[ItemModel]:
        return self.db.query(ItemModel).filter(ItemModel.id == item_id).first()

    def create_item(self, item: ItemCreate) -> ItemModel:
        db_item = ItemModel(
            name=item.name,
            description=item.description,
            price=item.price
        )
        self.db.add(db_item)
        self.db.commit()
        self.db.refresh(db_item)
        return db_item

    def update_item(self, item_id: int, item: ItemUpdate) -> Optional[ItemModel]:
        db_item = self.get_item(item_id)
        if db_item:
            for key, value in item.dict().items():
                setattr(db_item, key, value)
            self.db.commit()
            self.db.refresh(db_item)
        return db_item

    def delete_item(self, item_id: int) -> bool:
        db_item = self.get_item(item_id)
        if db_item:
            self.db.delete(db_item)
            self.db.commit()
            return True
        return False

# 创建数据库实例
db = Database() 